//
//  AddTagViewController.m
//  SoundPill
//
//  Created by 宋旭东®Des on 15/2/3.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "AddTagViewController.h"
#import "ZFTokenField.h"
#import "TokenView.h"
#import "AFNetworking.h"
#import "HotTagCollectionViewCell.h"
#import "AppDelegate.h"
#import "AttentionPersonViewController.h"
#import "JCAlertView.h"
@interface AddTagViewController ()<ZFTokenFieldDataSource,
    ZFTokenFieldDelegate,
    UITextFieldDelegate,
    UICollectionViewDataSource,
    UICollectionViewDelegateFlowLayout>
{
    UIFont *font;
    float fieldWidth;
    float fieldX;
    NSMutableArray *textarray;
    NSString *filePath;
}
@property (strong, nonatomic) ZFTokenField *tokenField;
@property (strong, nonatomic) NSMutableArray *tokens;
@property (strong, nonatomic) NSMutableArray *tokenHistroy;
//@property (strong, nonatomic) UIAlertView *textAlert;
//@property (strong, nonatomic) UIAlertView *tagAlert;
@property (strong, nonatomic) UITextField *tempField;
@property (strong, nonatomic) UIButton *rightButton;
//热门标签
@property (strong, nonatomic) UICollectionView *HotTagView;
@end

@implementation AddTagViewController
- (instancetype)initWithTitle:(NSString *)title
{
    self = [super init];
    if (self) {
        self.title = title;
        self.tokens = [NSMutableArray array];
        textarray = [NSMutableArray array];
        [self getHotTags];
        if (![title isEqualToString:@"标签"]) {
            [self getAttentedTags];
        }
    }
    return self;
}

#pragma mark -
#pragma mark 请求热门标签
- (void)getHotTags{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults objectForKey:@"authorization"];
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *url = nil;
    if ([self.title isEqualToString:@"标签"]) {
        url = @"http://123.57.1.143/api/tag/recommand";
    } else {
        url = @"http://123.57.1.143/api/tag/reg";
    }
    [manager GET:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *temp in array) {
            if ([self.title isEqualToString:@"标签"]) {
                [textarray addObject:[temp objectForKey:@"name"]];
            } else {
                [textarray addObject:temp];
            }
        }
        for (int i = 0; i<_tokens.count; i++) {
            NSDictionary *dic = _tokens[i];
            if ([textarray containsObject:dic]) {
                [textarray removeObject:dic];
                if (_HotTagView) {
                    [_HotTagView reloadData];
                }
            }
        }
        [_HotTagView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)getAttentedTags
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/tag", [[NSUserDefaults standardUserDefaults] valueForKey:@"uid"]];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject isKindOfClass:[NSArray class]]) {
            NSArray *tagArray = [responseObject objectForKey:@"data"];
            [_tokens addObjectsFromArray:tagArray];
        }
        for (int i = 0; i<_tokens.count; i++) {
            NSDictionary *dic = _tokens[i];
            if ([textarray containsObject:dic]) {
                [textarray removeObject:dic];
                if (_HotTagView) {
                    [_HotTagView reloadData];
                }
            }
        }
        [_tokenField reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if (_tokens.count > 0) {
        _rightButton.hidden = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    if ([self.title isEqualToString:@"标签"]) {
        NSFileManager *manager = [NSFileManager defaultManager];
        NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        // 传递 0 代表是找在Documents 目录下的文件。
        NSString *documentDirectory = [directoryPaths objectAtIndex:0];
        filePath = [documentDirectory stringByAppendingPathComponent:@"tagHistory"];
        if ([self.title isEqualToString:@"标签"]) {
            if (![manager fileExistsAtPath:filePath]) {
                [manager createFileAtPath:filePath contents:nil attributes:nil];
                self.tokenHistroy = [[NSMutableArray alloc] init];
            } else {
                self.tokenHistroy = [NSMutableArray arrayWithContentsOfFile:filePath];
                if (_tokenHistroy == nil) {
                    _tokenHistroy = [[NSMutableArray alloc] init];
                } else {
                    [textarray addObjectsFromArray:_tokenHistroy];
                    [_HotTagView reloadData];
                }
            }
        } else {
        }
    }
    [self createNavigationView];
    [self createZFToken];
    [self createHotTag];
//    [self createAlert];
    // Do any additional setup after loading the view.
}

- (void)createNavigationView
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.tag = 36;
    if ([self.title isEqualToString:@"标签"] || [self.title isEqualToString:@"已关注标签"]) {
        [leftButton setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    } else {
        [leftButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    }
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    [leftButton addTarget:self action:@selector(touchNavigationButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;

    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightButton.tag = 45;
    [_rightButton setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    _rightButton.frame = CGRectMake(0, 0, 30, 30);
    [_rightButton addTarget:self action:@selector(touchNavigationButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
    self.navigationItem.rightBarButtonItem = backItem;
    if (_tokens.count == 0) {
        _rightButton.hidden = YES;
    }
}

#pragma mark -
#pragma mark 导航栏按钮方法
- (void)touchNavigationButton:(UIButton *)sender
{
    if ([self.title isEqualToString:@"标签"]) {
        if (_tokenField.textField.text.length > 0) {
            [_tokens addObject:_tokenField.textField.text];
            [_tokenField reloadData];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"tagArray" object:_tokens];
        [self.tokenField.textField resignFirstResponder];
        [_tokenHistroy writeToFile:filePath atomically:YES];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        if (sender.tag == 45) {
            NSMutableArray *tagIDArray = [[NSMutableArray alloc] init];
            for (NSDictionary *tag in _tokens) {
                NSString *tagid = [tag valueForKey:@"id"];
                [tagIDArray addObject:tagid];
            }
            NSDictionary *tagDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:tagIDArray, @"tags", nil];
            
            NSString *url = @"http://123.57.1.143/api/tag/add";
            NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
            [manager POST:url parameters:tagDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
        if ([self.title isEqualToString:@"已关注标签"]) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            AttentionPersonViewController *indicateVC = [[AttentionPersonViewController alloc] init];
            [self presentViewController:indicateVC animated:YES completion:nil];
        }
    }
}

#pragma mark -
#pragma mark 创建ZFToken
- (void)createZFToken
{
    self.tokenField = [[ZFTokenField alloc] initWithFrame:CGRectMake(5, 7, self.view.frame.size.width - 10, self.view.frame.size.height / 3 - 30)];
    _tokenField.backgroundColor = [UIColor whiteColor];
    _tokenField.userInteractionEnabled = YES;
    _tokenField.delegate = self;
    _tokenField.dataSource = self;
    [_tokenField.textField setReturnKeyType:UIReturnKeyDone];
    [self.view addSubview:_tokenField];
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(5, _tokenField.frame.origin.y + _tokenField.frame.size.height + 5 , self.view.frame.size.width - 10, 5)];
    line.image = [UIImage imageNamed:@"gray"];
    [self.view addSubview:line];
    if ([self.title isEqualToString:@"标签"]) {
        _tokenField.textField.userInteractionEnabled = YES;
        [self.tokenField.textField becomeFirstResponder];
    } else {
        _tokenField.textField.userInteractionEnabled = NO;
    }
    
}

#pragma mark -
#pragma mark ZFToken DataSource
- (CGFloat)lineHeightForTokenInField:(ZFTokenField *)tokenField
{
    return 25;
}

- (NSUInteger)numberOfTokenInField:(ZFTokenField *)tokenField
{
    return _tokens.count;
}

- (UIView *)tokenField:(ZFTokenField *)tokenField viewForTokenAtIndex:(NSUInteger)index
{
    TokenView *tokenView = [[TokenView alloc] init];
    tokenView.userInteractionEnabled = YES;
    tokenView.backgroundColor = [UIColor whiteColor];
//    tokenView.layer.cornerRadius = 10;
    tokenView.layer.borderColor = [UIColor blackColor].CGColor;
    tokenView.layer.borderWidth = 2;
    tokenView.tokenLabel.frame = CGRectMake(10, 0, self.view.frame.size.width, 25);
    tokenView.tokenLabel.textColor = [UIColor blackColor];
    if ([self.title isEqualToString:@"标签"]) {
        tokenView.tokenLabel.text = self.tokens[index];
    } else {
        tokenView.tokenLabel.text = [_tokens[index] valueForKey:@"name"];
    }
    CGSize size = [tokenView.tokenLabel sizeThatFits:CGSizeMake(1000, 25)];
    tokenView.frame = CGRectMake(0, 0, size.width + 20, 25);
    UIButton *deleteTag = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteTag.backgroundColor = [UIColor clearColor];
    deleteTag.alpha = 0.3;
    deleteTag.layer.cornerRadius = 10;
    deleteTag.tag = index;
    deleteTag.frame = CGRectMake(0, 0, tokenView.bounds.size.width, tokenView.bounds.size.height);
    [deleteTag addTarget:self action:@selector(deleteTag:) forControlEvents:UIControlEventTouchUpInside];
    [tokenView addSubview:deleteTag];
    return tokenView;
}
#pragma mark - ZFTokenField Delegate
- (CGFloat)tokenMarginInTokenInField:(ZFTokenField *)tokenField
{
    return 2;
}

- (void)tokenField:(ZFTokenField *)tokenField didReturnWithText:(NSString *)text
{
    if (![text isEqualToString:@""]) {
        if (text.length <= 20) {
            if (_tokens.count < 5) {
                [self.tokens addObject:text];
                [tokenField reloadData];
                [self.tokenField.textField becomeFirstResponder];
                if (_tokenHistroy.count > 0) {
                    if (![_tokenHistroy containsObject:text] && ![text isEqualToString:@"记录"] &&
                        ![text isEqualToString:@"谈话"] &&
                        ![text isEqualToString:@"点评"] &&
                        ![text isEqualToString:@"音乐"] &&
                        ![text isEqualToString:@"读书"] &&
                        ![text isEqualToString:@"其他"] &&
                        ![text isEqualToString:@"段子"] &&
                        ![text isEqualToString:@"故事"] &&
                        ![text isEqualToString:@"旅行"] &&
                        ![text isEqualToString:@"买卖"] &&
                        ![text isEqualToString:@"观点"] &&
                        ![text isEqualToString:@"电影"] &&
                        ![text isEqualToString:@"话题"] &&
                        ![text isEqualToString:@"教学"]) {
                        if (_tokenHistroy.count < 7) {
                            [_tokenHistroy addObject:text];
                        } else {
                            [_tokenHistroy removeObjectAtIndex:0];
                            [_tokenHistroy addObject:text];
                        }
                    }
                } else {
                    [_tokenHistroy addObject:text];
                }
            } else {
                [JCAlertView showOneButtonWithTitle:@"提示" Message:@"最多可添加5个标签" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                    
                }];
                tokenField.textField.text = @"";
                [tokenField reloadData];
            }
        }
        _rightButton.hidden = NO;
    }
}

- (void)tokenField:(ZFTokenField *)tokenField didRemoveTokenAtIndex:(NSUInteger)index
{
    [self.tokens removeObjectAtIndex:index];
    [_tokenField reloadData];
    if (_tokens.count == 0) {
        _rightButton.hidden = YES;
    }
}

- (BOOL)tokenFieldShouldEndEditing:(ZFTokenField *)textField
{
    return YES;
}

- (void)tokenField:(ZFTokenField *)tokenField didTextChanged:(NSString *)text{
    [self textLength:text];
}

- (void)deleteTag:(UIButton *)sender{
    _rightButton.hidden = NO;
        TokenView *token = (TokenView *)sender.nextResponder;
    if (token.state==0) {
        token.frame = CGRectMake(token.frame.origin.x, token.frame.origin.y, token.frame.size.width +20, token.frame.size.height);
    UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
    del.frame = CGRectMake(token.frame.size.width - 23, 0, 20, token.frame.size.height - 3);
    del.backgroundColor = [UIColor clearColor];
    del.tag = sender.tag;
    del.titleLabel.font = [UIFont systemFontOfSize:25];
    [del setTitle:@"×" forState:UIControlStateNormal];
    [del setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [del addTarget:self action:@selector(removeTagFromToken:) forControlEvents:UIControlEventTouchUpInside];
    [token addSubview:del];
        token.state = 1;
    }
}
- (void)removeTagFromToken:(UIButton *)sender
{
    if (![self.title isEqualToString:@"标签"]) {
        [textarray addObject:_tokens[sender.tag]];
        [_HotTagView reloadData];
    }
    [_tokens removeObjectAtIndex:sender.tag];
    [_tokenField reloadData];
}
- (void)textLength:(NSString *)text{
    if (text.length > 20) {
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"每个标签最多可 输入20字" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
//        [_textAlert show];
        _tokenField.textField.text = @"";
    }
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.tokenField.textField resignFirstResponder];
}
#pragma mark - 
#pragma mark 热门标签列表
- (void)createHotTag
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
//    layout.itemSize = CGSizeMake(100, 100);
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
//    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
//    layout.estimatedItemSize = CGSizeMake(300, 30);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5 ;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 0, 5);
    self.HotTagView = [[UICollectionView alloc] initWithFrame:CGRectMake(5, _tokenField.frame.origin.y + _tokenField.frame.size.height + 15, self.view.frame.size.width - 10, self.view.frame.size.height / 3 - 50) collectionViewLayout:layout];
    _HotTagView.delegate = self;
    _HotTagView.dataSource = self;
    _HotTagView.scrollEnabled = NO;
    _HotTagView.backgroundColor = [UIColor clearColor];
    //注册 cell
    [_HotTagView registerClass:[HotTagCollectionViewCell class] forCellWithReuseIdentifier:@"HotTagItem"];
    [self.view addSubview:_HotTagView];
}

#pragma mark -
#pragma mark collectionView 协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [textarray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotTagCollectionViewCell *hotTagItem = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotTagItem" forIndexPath:indexPath];
    hotTagItem.backgroundColor = [UIColor whiteColor];
    if ([self.title isEqualToString:@"标签"]) {
        hotTagItem.hotTagText.text = textarray[indexPath.row];
    } else {
        hotTagItem.hotTagText.text = [textarray[indexPath.row] valueForKey:@"name"];
    }
    hotTagItem.hotTagText.textColor = [UIColor blackColor];
    hotTagItem.layer.borderWidth = 2;
    hotTagItem.layer.borderColor = [UIColor blackColor].CGColor;
//    hotTagItem.layer.cornerRadius = 10;
    return hotTagItem;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = nil;
    if ([self.title isEqualToString:@"标签"]) {
        str = textarray[indexPath.row];
    } else {
        str = [textarray[indexPath.row] valueForKey:@"name"];
    }
    CGSize titlesize = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:16]}];
    CGSize newSize = CGSizeMake(titlesize.width + 10, titlesize.height + 10);
    return newSize;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([self.title isEqualToString:@"标签"]) {
        if (_tokens.count < 5) {
            [self.tokens addObject:[textarray objectAtIndex:indexPath.row]];
            _rightButton.hidden = NO;
        } else {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"最多可添加5个标签" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }
    } else {
        if (![self.tokens containsObject:textarray[indexPath.row]]) {
            [self.tokens addObject:textarray[indexPath.row]];
            [textarray removeObjectAtIndex:indexPath.row];
            [collectionView reloadData];
            _rightButton.hidden = NO;
        }
    }

    [self.tokenField reloadData];
}

#pragma mark -
#pragma mark alertView
- (void)createAlert
{
//    self.textAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"每个标签最多可 输入20字" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    self.tagAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"最多可添加5个标签" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
